package com.finance.rule.computer;

import com.finance.base.enums.MajorTypeEnum;
import com.finance.report.bean.pojo.LogisticsData;
import com.finance.report.service.ILogisticsDataService;
import net.sf.json.JSONArray;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 当当网主拖件规则
 */
@Service
@Scope("prototype")
class DangdangAnalyzer implements IMajorAnalyzer,Serializable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ILogisticsDataService logisticsDataService;

    @Override
    public MajorTypeEnum majorTyeOf(LogisticsData data) {
        if(this.isSingle(data)) {
            return MajorTypeEnum.MAJOR;
        }
            List<LogisticsData> list = this.getOtherParts(data);
            list.add(data);
            this.logger.info("{}的其他部分{}",data.getWaybillNum(), JSONArray.fromObject(list).toString());
        if(data.getWaybillNum().endsWith("-2")) {
            return MajorTypeEnum.ZERO;
        }
            Collections.sort(list, new Comparator<LogisticsData>() {
            @Override
            public int compare(LogisticsData o1, LogisticsData o2) {
                int result = o1.getWaybillNum().compareTo(o2.getWaybillNum());
                DangdangAnalyzer.this.logger.info("{}和{}比较结果{}",new String[]{o1.getWaybillNum(),o2.getWaybillNum(),result + ""});
                return result;
            }
        });
        return list.get(0).equals(data) ? MajorTypeEnum.MAJOR : MajorTypeEnum.DRAG;
    }

    @Override
    public boolean isSingle(LogisticsData data) {
        return CollectionUtils.isEmpty(this.getOtherParts(data));
    }

    @Override
    public List<LogisticsData> getOtherParts(LogisticsData logisticsData) {
        this.logger.info("获取{}的其他部分",logisticsData.getWaybillNum());
        String tableName = this.logisticsDataService.getDataTableName(logisticsData.getSignTime());
        List<LogisticsData> list = this.logisticsDataService.getByBusinessCode(logisticsData.getBusinessCode(),tableName);
        if(CollectionUtils.isEmpty(list) || list.size() < 1) {
            return new ArrayList<LogisticsData>();
        }
            List<LogisticsData> result = new ArrayList<>();
            result.addAll(list);
            result.remove(logisticsData);
            this.logger.info("{}的其他部分数量为{}",logisticsData.getWaybillNum(),list.size());
        return result;
    }

    @Override
    public void init(String json) {

    }
}
